const common = require("./webpack.common");
const { merge } = require("webpack-merge");

const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const TerserJSPlugin = require('terser-webpack-plugin');
const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

const path = require("path");

module.exports = merge(common, {
  mode: "production",
  optimization: {
    // 模块只导出被使用的成员
    usedExports: true,
    // 压缩输出结果
    minimizer: [
      new TerserJSPlugin({}),
      new OptimizeCSSAssetsPlugin({}),
    ],
    splitChunks: {
      // 自动提取所有公共模块到单独 bundle
      chunks: "all",
      cacheGroups: {
        styles: {
          name: "styles",
          test: /\.(le|c)ss$/,
          chunks: "all",
          enforce: true,
        },
      },
    },
  },
  module: {
    rules: [
      {
        test: /\.(le|c)ss$/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
          },
          "css-loader",
          "less-loader",
        ],
      },
    ],
  },
  plugins: [
    new CleanWebpackPlugin(),
    new CopyWebpackPlugin({
      patterns: [
        "public",
        {
          from: path.join(__dirname, "/src/assets"),
          to: path.join(__dirname, "/dist/static/assets"),
        },
      ],
    }),
    new MiniCssExtractPlugin({
      // 选项类似于webpackoptions.output中的相同选项
      // 这两个选项都是可选的
      filename: "static/css/[name].[hash:8].css",
      chunkFilename: "static/css/[name].[hash:8].css",
    }),
  ],
});
